// 添加日期范围
import { Ref, ref } from 'vue'
import { NodeType, SysMenu } from '@/api/system/menu/type.ts'
import { ElMessage, ElMessageBox } from 'element-plus'
import { reqBaseData } from '@/api/type.ts'




/**
 * 获取当前的服务地址
 */
export  function getServerUrl() {
  return import.meta.env.VITE_APP_BASE_API
}



export function addDateRange(params, dateRange, propName) {
  if (typeof propName === 'undefined') {
    // 添加到集合中
    params['beginTime'] = dateRange.value[0]
    params['endTime'] = dateRange.value[1]
  } else {
    // 添加到集合中
    params['begin' + propName] = dateRange.value[0]
    params['end' + propName] = dateRange.value[1]
  }
  return params
}

interface Config {
  id: string
  parentId: string
  childrenList: string
}

/**
 * 构造树
 * @param data
 * @param id
 * @param parentId
 * @param children
 */
export const handleTree = (
  data: any[],
  id?: string,
  parentId?: string,
  children?: string,
) => {
  const config: Config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children',
  }

  console.log('config', config)

  const childrenListMap: Record<string, any[]> = {}
  const nodeIds: Record<string, any> = {} /**/
  const tree: any[] = []

  for (let i = 0; i < data.length; i++) {
    const d = data[i]
    const parentId = d[config.parentId]
    if (!childrenListMap[parentId]) {
      childrenListMap[parentId] = []
    }
    nodeIds[d[config.id]] = d
    childrenListMap[parentId].push(d)
  }

  console.log('childrenListMap', childrenListMap)

  for (let i = 0; i < data.length; i++) {
    const d = data[i]
    const parentId = d[config.parentId]
    if (!nodeIds[parentId]) {
      tree.push(d)
    }
  }

  console.log('tree', tree)

  for (let i = 0; i < tree.length; i++) {
    adaptToChildrenList(tree[i])
  }

  function adaptToChildrenList(o: any) {
    if (childrenListMap[o[config.id]]) {
      o[config.childrenList] = childrenListMap[o[config.id]]
    }
    if (o[config.childrenList]) {
      for (let i = 0; i < o[config.childrenList].length; i++) {
        const c = o[config.childrenList][i]
        adaptToChildrenList(c)
      }
    }
  }
  console.log('tree', tree)

  return tree
}

// 表单重置
export function resetForm(refName: Ref<any>) {
  if (refName.value) {
    refName.value.resetFields()
  }
}

/**
 * 合并的方法
 * @param source 源数据
 * @param target 操作数据
 */
export const mergeRecursive = (source: any, target: any) => {
  for (var p in target) {
    try {
      if (target[p].constructor == Object) {
        source[p] = mergeRecursive(source[p], target[p])
      } else {
        source[p] = target[p]
      }
    } catch (e) {
      source[p] = target[p]
    }
  }
  return source
}

//集中处理只有返回成功和失败信息的result
export const onlyMessageResult = (
  result: reqBaseData,
  successMsg: string,
  errorMsg: string,
) => {
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: successMsg,
    })
  } else {
    ElMessage({
      type: 'error',
      message:
        result.message != null ? result.message : result.code + ' ' + errorMsg,
    })
    console.log(result.message)
  }
}

/*对表格的行进行渲染*/
/**
 * 染色
 * @param row
 * @param rowIndex
 */
export const tableRowClassName = ({ row }: { row: any }) => {
  if (row.status === '1') {
    return 'warning-row'
  } else if (row.status === '0') {
    return 'success-row'
  }
  return ''
}

/**
 * 构建树形结构生成树
 * @param options
 */
const filterMethod = (options: any) => {
  let list: NodeType[] = []
  ;[...options].filter((item: any) => {
    let node: NodeType = {
      value: 0,
      label: '',
      length: 0,
      children: [],
    }
    node.value = item.id
    node.label = item.menuName
    node.length = item.children.length == undefined ? 0 : item.children.length
    if (item.children) {
      node.children = getChildMethod(item.children)
    }
    list.push(node)
  })
  const data = [
    {
      value: 0,
      label: '主类目',
      length: list.length,
      children: list,
    },
  ]
  return data
}
const getChildMethod = (item: any) => {
  let child: any = []
  item.filter((it: any) => {
    const node = ref({
      value: undefined,
      length: undefined,
      label: null,
      children: [],
    })
    node.value.value = it.id
    node.value.label = it.menuName
    node.value.length = it.children.length
    if (it.children) {
      node.value.children = getChildMethod(it.children)
    }
    child.push(node)
  })
  return child
}


/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + "=";
    if (value !== null && value !== "" && typeof (value) !== "undefined") {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
            let params = propName + '[' + key + ']';
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result
}
